const http = require("http");
const fs = require("fs")
const ws = require("socket.io")
const server = http.createServer((req, res)=>{
    const txt = fs.readFileSync("./index.html",{encoding: 'utf-8'});
    res.end(txt)
})

server.listen(3333,()=>{
    console.log('sucess running 3333');
})



const io = ws(server);

//服务端监听客户端连接事件
io.on("connection",(socket)=>{
    let username = null;
    let named = null;
    //获取当前用户量
    const count2 = io.of("/").sockets.size;
    console.log(`新用户进入，当前聊天室用户量：${count2}`);
    io.emit(`新用户进入，当前聊天室用户量：${count2}`);

    socket.on("disconnection",()=>{
        console.log(`用户离开，当前聊天室用户量：${count2}`);
        // io.emit('disconnection',uuid)

    })
    socket.on("join",(name)=>{
        console.log(name,'sssssssssaaaaaa');
        if(name == '' || name == null) return
        named = name;
        // if(named.length > 2){
        //     named = named.substring(0,2);
        // }
        username = (`<span id="infos">${named}</span>`);
        io.emit("join",name)
        fs.appendFile("blog.txt",`${named}上线了！\r\n`,(err,data)=>{
	if(err) throw err
	console.log(data)
        })
    })

    const ips = socket.handshake.address;
    socket.on("message", msg => {
        console.log(msg,'sssssssss');
        if(msg == '' || msg == null) return
        //msg为客户端发过来数据      
        io.emit('message',(username + msg))
        const times = new Date();
        const blogInfo = `${times}\r\n${named}:  ${msg}\r\n`
        const write = fs.appendFile("blog.txt",blogInfo,(err,data)=>{
	if(err) throw err
	console.log(data,'回调数据')
         });
	console.log(write)
    })
})
